package cs236369.hw5.rest;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Consumes;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;

import org.apache.commons.httpclient.HttpStatus;
import org.apache.log4j.Logger;

import cs236369.hw5.Hw5Conf;
import cs236369.hw5.db.DbHandler;
import cs236369.hw5.db.DbHandlerImp;
import cs236369.hw5.db.UserRegistrationException;
import cs236369.hw5.db.beans.DbUser;
import cs236369.hw5.rest.beans.UserRegisterBean;

@Path("/register-api")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public class RegisterApi
{

	private DbHandler db = new DbHandlerImp();

	/**
	 * register a new user...
	 * 
	 * @param user is the user name
	 * @param password is the password...
	 */
	@PUT
	@Path("/register/user")
	public void registerUser(@Context HttpServletRequest req, @Context HttpServletResponse res, UserRegisterBean user)
	{
		register(res, user, "user");
	}

	/**
	 * register a new admin... <br>
	 * invalidate the old admin session...
	 * 
	 * @param user is the user name
	 * @param password is the password...
	 */
	@PUT
	@Path("/register/admin")
	public void registerAdmin(@Context HttpServletRequest req, @Context HttpServletResponse res, UserRegisterBean user)
	{
		if (Hw5Conf.getAdminPass().equals(user.getAdminPassword()))
		{
			register(res, user, "admin");
		}

	}

	private void register(HttpServletResponse res, UserRegisterBean user, String role)
	{
		Logger logger = Logger.getLogger(getClass());
		try
		{
			if (null == user.getUsername() //
			    || null == user.getPassword() //
			    || user.getUsername().isEmpty() //
			    || user.getPassword().isEmpty())
			{
				logger.warn("[WARN] user is trying to register with wrong input");
				int stat = HttpStatus.SC_ACCEPTED;
				res.sendError(stat, HttpStatus.getStatusText(stat));
			}

			try
			{
				logger.info("generating new user: " + user.getUsername());
				DbUser u = new DbUser(user);
				logger.info("adding role: " + role + " for user: " + user.getUsername());
				u.addRole(role);
				logger.info("saving user to db: " + user.getUsername());
				db.saveNewUser(u);
				logger.info("[OK] " + user.getUsername() + ": was created successfully");
			}
			catch (UserRegistrationException e)
			{
				logger.warn("[FAIL] can't register user: " + user.getUsername());
				int stat = HttpStatus.SC_CONFLICT;
				res.sendError(stat, e.getMessage());	
			}
			catch (Exception e)
			{
				logger.error("[FAIL] can't register user: " + user.getUsername(), e);
				int stat = HttpStatus.SC_INTERNAL_SERVER_ERROR;
				res.sendError(stat, HttpStatus.getStatusText(stat));
			}
		}
		catch (IOException e1)
		{
			logger.warn("[FAIL] can't send error", e1);
		}

	}

}
